import {
  Router
} from 'express'
const router = Router()
import config from 'config'
import mysql from '../../libs/mysql'
import util from '../../util'
router.get('/',async (req,res,next)=>{
  let myConnect = await mysql.getConnect();
  let sql = `select * from tags`;
  let result = await mysql.query(myConnect,sql);
  await mysql.release(myConnect);
  res.render('tags', {
    'module_dir': config.get('admin.route'),
    list:result
  })
})
router.get('/:id',async (req,res,next)=>{
  let id = req.params['id'];
  let name =""
  if(id){
    let myConnect = await mysql.getConnect();
    let sql = `select * from tags where id = ${id}`;
    let result = await mysql.query(myConnect,sql);
    await mysql.release(myConnect);
    if(result.length){
      name = result[0]['name']
    }
  }
  return res.render('tags_edit', {
    module_dir: config.get('admin.route'),
    id,
    name
  })
})
router.post('/edit',async (req,res,next)=>{
  let {name,id} = req.body;
  let userid = config.get('user_id') || req.session.user.id
  if(userid){
    let myConnect = await mysql.getConnect();
    let sql='';
    let params = null;
    if(id==0){
      sql = `insert into tags(user_id,name) values (?)`;
      params = [userid,name];
    }else{
      sql = `UPDATE tags SET name = '${name}' WHERE id = ${id}`;
    }
    let result = await mysql.query(myConnect,sql,params);
    console.log(result)
    await mysql.release(myConnect);
    if(result.affectedRows===1){
      return res.send(util.resSuccess({
        data:result
      }))
    }
    return res.send(util.resError({
      code:'user_id',
      msg:"插入错误"
    }))
  }else{
    return res.send(util.resError({
      code:'user_id',
      msg:"请登录"
    }))
  }
 
})
export default router;